<template>
  <div>
    <el-breadcrumb separator="/" style="margin-bottom:20px;font-size:14px;">
      <el-breadcrumb-item :to="{ path: '/tahome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>报表上传</el-breadcrumb-item>
    </el-breadcrumb>
    <el-tabs type="border-card">
      <el-tab-pane label="季报上传">
        <div style="padding:20px 20px;">
          <el-row>
            <el-col :span="15">
              <el-card class="box-card" :body-style="{height:'200px',backgroundColor:'#ffffff'}" style="background-color: #EFF2F7;">
                <div slot="header" class="clearfix">
                  <span>
                    <i class="el-icon-caret-right" style="color:red;"></i>上传季报</span>
                </div>
                <el-upload class="upload-demo"  :on-exceed="warningExceed" :limit=3 ref="upload" action="ta/excelreport" :before-upload="beforeAvatarUpload" :on-remove="handleRemove" :on-change="handleChange" :on-success="handleSuccess" :on-error="handleError" :http-request="handleRequest" :multiple="true" name="excels" :file-list="tempFileList" :auto-upload="false">
                  <el-button slot="trigger" type="primary" :disabled="canUpload">选取季报文件</el-button>
                  <el-button style="margin-left: 10px;" type="success" :disabled="sysinfo.state == 0 && (process.state == 0 || process.state == 3)? false:true" @click="submitUpload">提交本次季报</el-button>
                  <div slot="tip" class="el-upload__tip" style="font-size:14px;">只能上传xlsx文件，且不超过2MB</div>
                </el-upload>
                <!--<v-file-upload></v-file-upload>-->
              </el-card>

            </el-col>
            <el-col :span="8" :offset="1">
              <el-card class="box-card" :body-style="{height:'200px',backgroundColor:'#ffffff'}" style="background-color: #EFF2F7;">
                <div slot="header" class="clearfix">
                  <span>
                    <i class="el-icon-caret-right" style="color:red;"></i>下载模板</span>
                </div>
                <ul class="results_doc">
                  <li>
                    <a href="/template/旅行社外联接待入境旅游情况季报表.xlsx">Excel外联接待入境旅游情况</a>
                  </li>
                  <li>
                    <a href="/template/旅行社组织出境旅游情况季报表.xlsx">Excel外联接待出境旅游情况</a>
                  </li>
                  <li>
                    <a href="/template/旅行社组织接待国内旅游情况季报表.xlsx">Excel组织接待国内旅游情况数据模板</a>
                  </li>
                </ul>
                <span style="padding-top:10px;color:red;">* 注意表名默认，不用改动</span>
              </el-card>
            </el-col>
          </el-row>
          <el-row style="padding-top:30px;">
            <el-col :span="24">
              <el-card class="box-card" :body-style="{backgroundColor:'#ffffff'}" style="background-color: #EFF2F7;">
                <div slot="header" class="clearfix">
                  <span>
                    <i class="el-icon-caret-right" style="color:red;"></i>上传说明</span>
                </div>
                <ul class="results_doc">
                  <li>
                    <span>上传的Excel格式必须和模板格式相同，不能更改原模板的格式；</span>
                  </li>
                  <li>
                    <span>每次上传的文件不要大于2M，否则有可能造成数据处理异常；</span>
                  </li>
                  <li>
                    <span>上传时请慎重操作，当入境、出境、国内三张表都上传后，请点击“提交本次季报”按钮；</span>
                  </li>
                </ul>
              </el-card>
            </el-col>
          </el-row>
        </div>

      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
const xhr = new XMLHttpRequest();
const formData = new FormData();
import { mapGetters, mapActions } from "vuex";
export default {
  created() {
    if (this.sysinfo.state === 1) {
      this.$alert("本季度季报上报还未开始", "提示", {
        dangerouslyUseHTMLString: true,
        confirmButtonText: "确定"
      });
    } else {
      this.getProcess().then(
        res => {
          if (this.process.state != 0 && this.process.state != 3) {
            this.$alert(
              "您当前季度季报已提交,当前状态为<strong style='color:" +
                this.process.color +
                "'>" +
                this.process.title +
                "</strong>，无法再次填报！",
              "提示",
              {
                dangerouslyUseHTMLString: true,
                confirmButtonText: "确定"
              }
            );
            return false;
          }
        },
        error => {}
      );
    }
  },
  computed: {
    ...mapGetters(["process", "sysinfo"])
  },
  data() {
    return {
      canUpload: false,
      tempFileList: []
    };
  },
  methods: {
    ...mapActions(["getProcess"]),
    submitUpload() {
      this.$refs.upload.submit();
    },
    beforeAvatarUpload(file) {
      if (this.process.state != 0 && this.process.state != 3) {
        this.$message({
          message: "本季度季报已提交正在审核中，不能重复提交！",
          type: "error"
        });
        return false;
      } else {
        const extension2 = file.name.split(".")[1] === "xlsx";
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!extension2) {
          this.$message.error("上传文件只能是xlsx 格式!");
        }
        if (!isLt2M) {
          this.$message.error("上传文件大小不能超过 2MB!");
        }
        return extension2 && isLt2M;
      }
    },
    handleChange(file, fileList) {
      if (fileList.length === 3) {
        this.canUpload = true;
      }
    },
    handleRemove(file, fileList) {
      if (fileList.length < 3) {
        this.canUpload = false;
      }
    },
    handleSuccess(response, file, fileList) {
      this.canUpload = false;
      if (response.errorCode) {
        if (response.errorCode === "0") {
          this.$message({
            message: response.data,
            type: "success"
          });
          this.getProcess();
        } else {
          this.$message({
            message: response.errorMessage,
            type: "error"
          });
        }
      }
      this.$refs.upload.clearFiles();
    },
    handleError(err, file, fileList) {
      this.$refs.upload.clearFiles();
      this.canUpload = true;
    },
    warningExceed(files, fileList) {
      this.$message({
        message: "最多上传三分表格，请谨慎操作！",
        type: "error"
      });
      return false;
    },
    handleRequest(option) {
      const allFileCount = $(".el-upload-list").find("li").length;
      if (allFileCount === 0) {
        this.$alert("请选择需要上传的文件！", "提示", {
          confirmButtonText: "确定",
          callback: action => {
            return false;
          }
        });
        
      }
      if (typeof XMLHttpRequest === "undefined") {
        return;
      }
      const action = option.action;

      if (xhr.upload) {
        xhr.upload.onprogress = function progress(e) {
          if (e.total > 0) {
            e.percent = e.loaded / e.total * 100;
          }
          option.onProgress(e);
        };
      }
      formData.append(option.filename, option.file);
      this.tempFileList.push(option.file);
      if (this.tempFileList.length < allFileCount) {
        return false;
      }
      xhr.onerror = function error(e) {
        option.onError(e);
      };

      xhr.onload = function onload() {
        if (xhr.status < 200 || xhr.status >= 300) {
          return option.onError(getError(action, option, xhr));
        }

        option.onSuccess(getBody(xhr));
      };
      if (this.tempFileList.length > 0) {
        xhr.open("post", action, true);

        if (option.withCredentials && "withCredentials" in xhr) {
          xhr.withCredentials = true;
        }

        const headers = option.headers || {};

        for (let item in headers) {
          if (headers.hasOwnProperty(item) && headers[item] !== null) {
            xhr.setRequestHeader(item, headers[item]);
          }
        }
        xhr.send(formData);
      }
    }
  }
};

function getError(action, option, xhr) {
  let msg;
  if (xhr.response) {
    msg = `${xhr.status} ${xhr.response.error || xhr.response}`;
  } else if (xhr.responseText) {
    msg = `${xhr.status} ${xhr.responseText}`;
  } else {
    msg = `fail to post ${action} ${xhr.status}`;
  }

  const err = new Error(msg);
  err.status = xhr.status;
  err.method = "post";
  err.url = action;
  return err;
}

function getBody(xhr) {
  const text = xhr.responseText || xhr.response;
  if (!text) {
    return text;
  }

  try {
    return JSON.parse(text);
  } catch (e) {
    return text;
  }
}
</script>
<style scoped>
input[type="file"] {
  display: none;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon p {
  margin-top: 20px;
}

.avatar-uploader-icon img {
  width: 66px;
  height: 66px;
}

.results_doc {
  margin: 0px 10px;
  padding-left: 10px;
}

.results_doc li {
  list-style-type: decimal;
  padding: 5px 0px;
}

.results_doc li span {
  font-size: 14px;
}
</style>
